<style>
  .mainForm .form-left {
    width: 50%;
    padding-left: 1rem;
    padding-right: 1rem;
    padding-top: 1rem;
  }

  .mainForm .form-right {
    width: 50%;
    padding-left: 1rem;
    padding-right: 1rem;
    padding-top: 1rem;
  }

  .table-title {
    margin-bottom: 20px;
  }

  .el-icon-delete {
    color: red;
    cursor: pointer;
  }

  .show-tree > div {
    width: 577px
  }

  .factory-tree {
    position: absolute;
    width: 660px;
    z-index: 99;
    border: 1px solid #dadada;
    border-radius: 10px;
    padding: 20px;
    height: 340px;
    bottom: -340px;
    overflow: auto;
    background: #fff;
  }

  .checkList .el-checkbox + .el-checkbox, .checkList .el-checkbox {
    margin-left: 15px;
  }

  .toggle-list {
    margin-left: 10px;
    color: #3a8ee6;
    cursor: pointer;
  }

</style>


<template>

  <div style="margin: 10px">
    <el-breadcrumb separator="/" class="submenu">
      <el-breadcrumb-item :to="{ path: '/Index' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>
        <a href="/">创建询价</a>
      </el-breadcrumb-item>
    </el-breadcrumb>

    <div class="main-table">
      <template>
        <el-tabs v-model="firstTableName" type="card" @tab-click="handleClick">
          <!--询价主信息-->
          <el-tab-pane label="询价主信息" name="rfqMainInfo">
            <el-form :model="rfqMainData" :inline="true">
              <div>
                <el-form-item label="标题" :label-width="formLabelWidth">
                  <el-input v-model="rfqMainData.psTitle" style="width:217px"></el-input>
                </el-form-item>
                <el-form-item label="关联项目/产品" :label-width="formLabelWidth">
                  <el-input v-model="rfqMainData.compliantProduct" style="width:217px"></el-input>
                </el-form-item>

              </div>
              <div>
                <el-form-item label="品类：" prop="categoryName" :label-width="formLabelWidth">
                  <select-tree :multiple="false" ref="selectTree" v-model="rfqMainData.categoryName"></select-tree>
                </el-form-item>
                <el-form-item label="采购组织" :label-width="formLabelWidth">
                  <el-select v-model="rfqMainData.purOrgId" placeholder="请选择"
                             @change="initGroupData(rfqMainData.purOrgId)">
                    <el-option v-for="item in purOrgData" :key="item.id" :label="item.purOrgName"
                               :value="item.id">
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="采购组" :label-width="formLabelWidth">
                  <el-select v-model="rfqMainData.purGroupId" placeholder="请选择">
                    <el-option v-for="item in purGroupData" :key="item.id" :label="item.purGroupName"
                               :value="item.id">
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="采购类型" :label-width="formLabelWidth">
                  <el-select v-model="rfqMainData.purchaseTypeId" placeholder="请选择">
                    <el-option v-for="item in  DicData.purchasetypeData" :key="item.id" :label="item.name"
                               :value="item.id"></el-option>
                  </el-select>
                </el-form-item>

              </div>
              <el-form-item label="报价截止时间" :label-width="formLabelWidth">
                <el-date-picker v-model="rfqMainData.quoLimitTime" type="date" value-format="yyyy-MM-dd" placeholder="选择日期时间" :picker-options="pickeroptions"></el-date-picker>
                <el-select v-model="quoLimitTimeStrTime" @change="AddTime(quoLimitTimeStrTime)"  placeholder="请选择">
                  <el-option v-for="item in 24" :key="item" :label="item+'时'" :value="item<10?`0${item}`:item"></el-option>
                </el-select>
              </el-form-item>
              <div>
                <el-form-item label="发送通知" :label-width="formLabelWidth">
                  <el-checkbox v-model="rfqMainData.sendNoticeTypes[0]">邮件</el-checkbox>
                  <el-checkbox v-model="rfqMainData.sendNoticeTypes[1]">短信</el-checkbox>
                </el-form-item>
                <el-form-item label="是否启用秘钥" :label-width="formLabelWidth">
                  <el-radio-group v-model="rfqMainData.secretKeyStatus">
                    <el-radio :label="1">是</el-radio>
                    <el-radio :label="0">否</el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item v-show="rfqMainData.secretKeyStatus" label="秘钥接收人" :label-width="formLabelWidth">
                  <el-select v-model="rfqMainData.secretKeyRecUserId" placeholder="请选择">
                    <el-option
                      v-for="item in rfqMainData.secretKeyRecUserIdItem"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value">
                    </el-option>
                  </el-select>
                </el-form-item>
              </div>
              <div>
                <el-form-item label="是否生成采购公告" :label-width="formLabelWidth">
                  <el-radio-group v-model="rfqMainData.noticFlag">
                    <el-radio :label="1">是</el-radio>
                    <el-radio :label="0">否</el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item label="是否周期采购" :label-width="formLabelWidth">
                  <el-radio-group v-model="rfqMainData.isPeriodic">
                    <el-radio :label="1">是</el-radio>
                    <el-radio :label="0">否</el-radio>
                  </el-radio-group>
                </el-form-item>


                <!-- 带上名称：purchaseTypeName-->
              </div>
              <div>
                <el-form-item label="是否单一来源" :label-width="formLabelWidth">
                  <el-radio-group v-model="rfqMainData.singleSourceFlag">
                    <el-radio :label="1">是</el-radio>
                    <el-radio :label="0">否</el-radio>
                  </el-radio-group>
                </el-form-item>
              </div>
              <div>
                <el-form-item label="单一来源凭证" v-if="rfqMainData.singleSourceFlag" :label-width="formLabelWidth">
                  <el-upload
                    style="width:540px"
                    class="upload-file"
                    ref="upload"
                    action="https://jsonplaceholder.typicode.com/posts/"
                    :limit="1"
                    :on-change="handleChange">
                    <el-button slot="trigger" type="primary">选取文件</el-button>
                  </el-upload>
                </el-form-item>
              </div>
              <div style="width:50%">
                <el-form-item label="公告：" prop="notice" class="w100">
                  <UE v-model="rfqMainData.notice" :config="config" ref="ue"></UE>
                </el-form-item>
              </div>
            </el-form>
          </el-tab-pane>
          <!--询价物料-->
          <el-tab-pane label="询价物料" name="rfqMaterial">
            <el-button type="primary" @click="addMaterial">新增</el-button>
            <!--<el-button type="primary">批量导入</el-button>-->
            <!--<el-button type="primary">移除有效价格</el-button>-->
            <!--物料列表数据-->
            <el-table :data="tableMaterialData" border="" style="width: 100%" max-height="500">
              <el-table-column prop="operation" label="操作" header-align="center">
                <template slot-scope="scope">
                  <!--   <el-checkbox label="" v-model="keys"></el-checkbox>-->
                  <el-button type="text" @click="delMaterialData(scope.$index)">删除</el-button>
                </template>
              </el-table-column>
              <el-table-column label="供货区域" align="center" prop="purOrgName"></el-table-column>
              <el-table-column label="工厂" align="center" prop="factoryName"></el-table-column>
              <el-table-column header-align="center" align="center" width="160" prop="materialId"
                               label="物料编码"></el-table-column>
              <el-table-column header-align="center" align="center" width="130" prop="materialName"
                               label="物料名称"></el-table-column>
              <el-table-column header-align="center" align="center" width="120" prop="planQty"
                               label="预计采购数量"></el-table-column>
              <el-table-column header-align="center" align="center" width="120" prop="materialUnit"
                               label="采购单位"></el-table-column>
              <el-table-column header-align="center" align="center" width="140" prop="templateId"
                               label="报价模板"></el-table-column>
              <el-table-column header-align="center" align="center" width="140" prop="priceStartDate"
                               label="价格实施开始日期"></el-table-column>
              <el-table-column header-align="center" align="center" width="140" prop="priceEndDate"
                               label="价格实施结束日期"></el-table-column>
              <el-table-column header-align="center" align="center" width="120" prop="quoteType"
                               label="报价类型"></el-table-column>
              <el-table-column header-align="center" align="center" width="120" prop="deliveryAddress"
                               label="交货地址"></el-table-column>
              <el-table-column header-align="center" align="center" width="120" prop="logisticsModeId"
                               label="物流方式"></el-table-column>
              <el-table-column header-align="center" align="center" width="120" prop="paymentTermsId"
                               label="付款方式"></el-table-column>
              <el-table-column header-align="center" align="center" width="120" prop="attachmentName"
                               label="附件"></el-table-column>
              <el-table-column header-align="center" align="center" width="120" prop="remarks"
                               label="备注"></el-table-column>
              <el-table-column header-align="center" align="center" width="120" v-if='isShow'
                               prop="quoteItems"></el-table-column>
            </el-table>
            <!--新增弹框---询价物料信息-->
            <el-dialog title="询价物料信息" :visible.sync="dialogFormVisible" center>
              <el-form :model="addMaterData" :rules="rules" ref="addOrUpdateForm" :inline="true">
                <el-form-item style="position:absolute;top: 40px;left: 122px;">
                  <el-checkbox v-model="checked" @change="changeMater">无料号</el-checkbox>
                </el-form-item>
                <el-form-item :label-width="formLabelWidth" label="工厂：" prop="showTextarea" style="width:100%"
                              class="show-tree">
                  <span @click.stop="togglePanel"><el-input v-model="addMaterData.showTextarea" readonly type="textarea"
                                                            :autosize="{ minRows: 2, maxRows: 10}"></el-input></span>
                  <div class="factory-tree" v-show="showTree" ref="shows">
                    <div v-for="m in categoryOptions" :key="m.id">
                      <div class="checkAll">
                        <el-checkbox v-model="m.checkAll" @change="(val)=>{handleCheckAllChange(val,m)}">
                          {{m.purOrgName}}
                        </el-checkbox>
                        <span v-if="!!m.factoryList.length" @click.stop="m.showList=!m.showList" class="toggle-list">{{!m.showList?'展开':'收起'}}</span>
                      </div>
                      <div class="checkList" v-show="m.showList">
                        <el-checkbox v-for="n in m.factoryList" v-model="n.checked" :key="n.id"
                                     @change="(val)=>{handleCheckedChange(val,m,n)}">{{n.factoryNameFull}}
                        </el-checkbox>
                      </div>
                    </div>
                  </div>
                </el-form-item>
                <el-form-item :label-width="formLabelWidth" label="物料编码：" prop="materialId" v-if="!checked">
                  <select-fac-material v-model="addMaterData.materialId" @on-selection-data="getRowData"
                                       :factoryIds="addMaterData.factIds"></select-fac-material>
                </el-form-item>
                <el-form-item :label-width="formLabelWidth" label="物料名称：" prop="materialName">
                  <el-input v-model="addMaterData.materialName" :disabled="!checked"></el-input>
                </el-form-item>
                <el-form-item :label-width="formLabelWidth" label="采购单位：" prop="materialUnit" v-if="checked">
                  <el-select v-model="addMaterData.materialUnit" placeholder="请选择" filterable>
                    <el-option v-for="item in utilList" :key="item.id" :label="item.name" :value="item.id"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item :label-width="formLabelWidth" label="采购单位：" prop="materialUnit" v-else>
                  <el-input v-model="addMaterData.materialUnit" :disabled="!checked"></el-input>
                </el-form-item>
                <el-form-item :label-width="formLabelWidth" label="库存单位：" prop="stockUnit" v-if="checked">
                  <el-select v-model="addMaterData.stockUnit" placeholder="请选择" filterable>
                    <el-option v-for="item in utilList" :key="item.id" :label="item.name" :value="item.id"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item :label-width="formLabelWidth" label="库存单位：" prop="stockUnit" v-else>
                  <el-input v-model="addMaterData.stockUnit" :disabled="!checked"></el-input>
                </el-form-item>

                <div>
                  <el-form-item label="数量" prop="planQty" :label-width="formLabelWidth">
                    <el-input v-model="addMaterData.planQty" style="width: 217px"></el-input>
                  </el-form-item>
                  <el-form-item label="报价模版" prop="templateId" :label-width="formLabelWidth">
                    <el-select v-model="addMaterData.templateId" placeholder="请选择" @change="changeValuetemplate">
                      <el-option v-for="item in DicData.quoteTemplateData" :key="item.id" :label="item.templateName"
                                 :value="item.id">
                      </el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item label="报价类型" prop="quoteType" :label-width="formLabelWidth">
                    <el-select v-model="addMaterData.quoteType" placeholder="请选择">
                      <el-option label="标准" value="1"></el-option>
                      <el-option label="委外" value="2"></el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item label="物流方式" prop="logisticsModeId" :label-width="formLabelWidth">
                    <el-select v-model="addMaterData.logisticsModeId" placeholder="请选择"
                               @change="changeValueLogisticsMode(addMaterData.logisticsModeId)">
                      <el-option v-for="item in DicData.MODE_OF_TRANSPORT" :key="item.id" :label="item.name"
                                 :value="item.id">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </div>
                <div>
                  <el-form-item label="付款方式" prop="paymentTermsId" :label-width="formLabelWidth">
                    <el-select v-model="addMaterData.paymentTermsId" placeholder="请选择"
                               @change="changeValue(addMaterData.paymentTermsId)">
                      <el-option v-for="item in DicData.paymentTermsData" :key="item.id" :label="item.name"
                                 :value="item.id">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </div>
                <div>
                  <el-form-item label="价格实施日期" :label-width="formLabelWidth">
                    <el-date-picker v-model="addMaterData.priceStartDate" type="date"
                                    placeholder="选择日期" :picker-options="pickeroptions" value-format="yyyy-MM-dd"
                                    style="width: 217px"></el-date-picker>
                    -
                    <el-date-picker v-model="addMaterData.priceEndDate"
                                    @change="checkEndDate(addMaterData.priceEndDate)" type="date"
                                    placeholder="选择日期" :picker-options="pickeroptions" value-format="yyyy-MM-dd"
                                    style="width: 217px"></el-date-picker>
                  </el-form-item>
                </div>
                <div>
                  <el-form-item label="交货地址" prop="deliveryAddress" :label-width="formLabelWidth">
                    <el-input v-model="addMaterData.deliveryAddress" style="width:540px"></el-input>
                  </el-form-item>
                </div>
                <div>
                  <el-form-item label="附件：" :label-width="formLabelWidth">
                    <el-upload style="width:540px" class="upload-file" ref="upload" action="" :limit="1"
                               :on-change="handleChange">
                      <el-button slot="trigger" type="primary">选取文件</el-button>
                    </el-upload>
                  </el-form-item>
                </div>
                <div>
                  <el-form-item label="备注" :label-width="formLabelWidth">
                    <el-input type="textarea" :rows="3" placeholder="请输入内容" style="width:540px"
                              v-model="addMaterData.remarks"></el-input>
                  </el-form-item>
                </div>
                <hr style="border: 0;border-bottom: 1px solid #ccc;margin: 0 5%">
                <br>
                <div>
                  <el-form-item label="分段报价" :label-width="formLabelWidth">
                    <el-switch v-model="isRecharging" @click="ClearMaterialData()">
                    </el-switch>
                  </el-form-item>
                </div>
                <div v-if="isRecharging">
                  <el-table :data="RechargingData" style="margin-left: 130px;width: 62%" border>
                    <el-table-column
                      prop="name"
                      align="center"
                      label="类型">
                    </el-table-column>
                    <el-table-column
                      prop="val"
                      align="center"
                      label="分段数量">
                    </el-table-column>
                    <el-table-column
                      prop="val"
                      align="center"
                      label="操作">
                      <template slot-scope="scope">
                        <el-button type="text" size="small" @click="delRechargingData(scope.$index)">删除
                        </el-button>
                      </template>
                    </el-table-column>
                  </el-table>
                </div>
                <div v-if="isRecharging" style="margin-top: 10px">
                  <el-form-item label="单次" :label-width="formLabelWidth">
                    <el-select v-model="RechargingName" placeholder="请选择">
                      <el-option label="单次" value="单次"></el-option>
                      <el-option label="累计" value="累计"></el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item label="分段数量" :label-width="formLabelWidth">
                    <el-input type="input" :rows="3" placeholder="请输入内容"
                              v-model="RechargingVal" prop="RechargingVal"></el-input>
                  </el-form-item>
                  <el-button type="primary" size="mini" icon="el-icon-plus" @click="addRechargingData()" title="新增一列"
                             circle></el-button>
                </div>
              </el-form>
              <div slot="footer" center class="dialog-footer">
                <el-button @click="submitMaterialData()" type="primary">暂 存</el-button>
              </div>
            </el-dialog>
          </el-tab-pane>
          <!--选择供应商-->
          <el-tab-pane label="选择供应商" name="rfqVendor">
            <bidVendors ref="trans"
                        @transAdd="addTrans" width="100%" :checkName="['vendorCode','vendorName']"
                        :title="{left:'可选供应商',right:'已选供应商'}" :isQsparams="false"
                        :searchForm="searchForm" :selectData="vendorsJsonStr" @radioChange="getRadioVal"
                        :url="lib.config.host.system + '/system/orgmgt/organization/queryForPsDatalist'">
            </bidVendors>
          </el-tab-pane>
        </el-tabs>
        <div slot="footer" class="dialog-footer">
          <el-button @click="submitAllData()" type="primary">保存</el-button>
        </div>
      </template>
    </div>
  </div>
</template>
<script>


  var dataAll = []
  import axios from 'axios';
  import bidVendors from '@/components/bid/bid/bidVendors.vue';
  import SelectFacMaterial from '@/components/bid/components/select-facMaterial';
  import SelectTree from '@/components/common/select-ext/select-tree.vue';
  import UE from '@/components/common/ue/ue.vue';
  import qs from 'qs';

  var dat = []
  export default {
    beforeDestroy() {
      this.hide()
    },
    components: {
      bidVendors,
      SelectFacMaterial,
      SelectTree,
      UE
    },
    data() {
      return {
        searchForm:[
          {key:'vendorSource',type:'',value:[]},
          {key:'vendorName',type:'text',placeholder:'请输入名称',value:''},
          {key:'sourceType',type:'radio',placeholder:'',value:2,child:[{label:1,value:'按品类'},{label:2,value:'按货源'}]}
        ],
        vendorsJsonStr :[],
        categoryprops: {
          label: 'purOrgName',
          value: 'id',
          children: 'factoryList'
        },
        showTree: false,
        categoryOptions: [],
        checkcategorysName: {},
        checked: false,
        utilList: [],
        mallFlag: 0,   //商城信息
        //付款方式    物流方式   字典信息
        DicData:
          [{
            paymentTermsData: '',
            materialUnitData: '',
            templateData: '',
            purchasetypeData: '',

          }],
        purOrgData: [],   //采购组织字典
        purGroupData: [],   //采购组字典
        rfqVendorsJsonStr: [],
        priceStartDateTime: '',
        priceEndDateTime: '',
        quoLimitTimeStrTime: '',
        vals: '',
        pickeroptions: {
          disabledDate(time) {
            return time.getTime() <= Date.now() - 8.64e7
          }
        },

        firstTableName: 'rfqMainInfo',
        isShow: false,
        dialogFormVisible: false,
        //询价主信息
        rfqMainData:
          {
            title: '',
            compliantProduct: '',
            purOrgId: '',
            purOrgName: '',
            purGroupId: '',
            purGroupName: '',
            enquiryWay: '1',
            resultNoticeType: '1',
            categoryId: '',
            categoryName: '',
            purchaseTypeId: '',
            purchaseTypeName: '',
            sourcingWay: 1,
            quoLimitTime: '',
            secretKeyStatus: 0,
            sendNoticeTypes: [0, 0],
            secretKeyRecUserId: [],
            noticFlag: 0,
            isPeriodic: 0,
            isFrame: 0,
            singleSourceFlag: 0,
            RechargingData: [],
            RechargingName: '单次',
            RechargingVal: '',
          },
        config: {
          initialFrameWidth: 1450,
          initialFrameHeight: 200,
          enableAutoSave: false
        },

        //物料信息
        isRecharging: false,
        addMaterData:
          {
            priceStartDate: '',
            priceEndDate: '',
            mouldFlag: 0,    //暂时为0
            paymentTermsName: '',
            sourceType: 0,
            showTextarea: '',
            materialId: "",
            factIds: [],
            materialCode: "",
            materialName: "",
            materialSpec: "",
            materialUnit: "",
            stockUnit: "",
            logisticsModeId: '',
            templateId: '',
            templateName: '',
            quoteType: '',
            paymentTermsId: '',

          },
        dialogForm: {},
        tableMaterialData: [],
        selectVendorData: [],
        vendorForm:
          {
            vendorSection: []
          },
        selectPurOrgId: '',
        selectCategoryId: '',
        selectData: [],
        formLabelWidth: '130px',
        rules:
          {
            RechargingVal: [{required: true, message: '请输入分段数量', trigger: 'change'}, {
              min: 1,
              max: 5,
              message: '长度在 1 到 5 位数字',
              trigger: 'blur'
            }],
            showTextarea: [],
            factoryName: [{required: true, message: '请选择采购组织', trigger: 'change'}],
            factoryId: [{required: true, message: '请选择工厂', trigger: 'change'}],
            materialCode: [{required: true, message: '请输入物料编码', trigger: 'change'}],
            materialId: [{required: true, message: '请选择物料编码', trigger: 'change'}],
            materialUnit: [{required: true, message: '请选择采购单位', trigger: 'change'}],
            materialName: [{required: true, message: '请输入物料名称', trigger: 'change'}],
            materialSpec: [{required: true, message: '请输入型号/规格', trigger: 'change'}],
            stockUnitCode: [{required: true, message: '请选择库存单位', trigger: 'change'}],
            templateId: [{required: true, message: '请选择库报价模版', trigger: 'change'}],
            logisticsModeId: [{required: true, message: '请选择物流方式', trigger: 'change'}],
            quoteType: [{required: true, message: '请选择报价类型', trigger: 'change'}],
            paymentTermsId: [{required: true, message: '请选择付款方式', trigger: 'change'}],
            planQty: [{required: true, message: '请输入采购量', trigger: 'change'}, {
              min: 1,
              max: 5,
              message: '长度在 1 到 5 位数字',
              trigger: 'blur'
            }],
            priceStartDate: [{required: true, message: '请选择价格实施日期', trigger: 'change'}],
            priceEndDate: [{required: true, message: '请选择价格实施日期', trigger: 'change'}],
            deliveryAddress: [{required: true, message: '请输入交货地址', trigger: 'change'}],

            remarks: []

          }
      }
    },
    created(){
      this.searchTrans();
    },

    // 监听品类下拉
    watch: {
      'rfqMainData.categoryName': function (val) {
        if (val) {
          let data = this.$refs['selectTree'].getResultData();
          //this.npcTaskForm.showvender=data.parentId||data.id||this.npcTaskForm.categoryId;
          this.rfqMainData.categoryId = data.id || this.rfqMainData.categoryId;
          this.selectCategoryId = data.id;
        } else {
          this.rfqMainData.categoryId = '';
        }
      }


    },

    // Add By masn 2017/6/7
    mounted() {
      this.initDatas()

      this.axios.post(this.lib.config.host.masterData + '/system/purOrgMgt/purOrg/getPurOrgWithFactory').then((res) => {
        this.categoryOptions = res.data.map(item => {
          item.factoryList.forEach(val => {
            val.checked = false;
          })
          const data = {
            ...item,
            showList: false
          }
          return data;
        });
      })
      this.$nextTick(() => {
        document.querySelector('body').addEventListener('click', this.handleBodyClick);
      })

    },
    methods: {
      handleClick(tab, event) {
        switch (this.firstTableName){
          case 'rfqVendor':
            //选择供应商后查询右侧穿梭框数据
            this.$refs.trans.initData();
            break;
          default:
            break;
        }
      },
      // 供应商选择
      getRadioVal(val){
        this.$refs.trans.searchFormat.vendorSource=[];
        if(val==1){
          this.$refs.trans.searchFormat.vendorSource=this.rfqMainData.categoryId?[this.rfqMainData.categoryId]:[];
        }else{
          this.tableMaterialData.forEach(item=>{
            if(!!item.materialId){
              this.$refs.trans.searchFormat.vendorSource.push(item.materialId)
            }
          })
          //this.$refs.trans.searchFormat.vendorSource=this.$refs.trans.searchFormat.vendorSource.join(',')
        }
      },
      togglePanel() {
        this.showTree ? this.hide() : this.show()
      },
      show() {
        this.showTree = true
        document.addEventListener('click', this.hidePanel, false)
      },
      hide() {
        this.showTree = false
        document.removeEventListener('click', this.hidePanel, false)
      },
      hidePanel(e) {
        if (!this.$refs.shows.contains(e.target)) {
          this.hide()
        }
      },
      // 初始化页面数据
      initDatas() {
        // 获取报价模版信息
        let url = this.lib.config.host.rfq + '/ctmgt/rfq/template/getAll';
        this.axios.get(url, {}).then((res) => {
          this.DicData.quoteTemplateData = res.data.result
        });
        //付款方式
        this.getDicData('PAYMENT_TERMS').then((data) => {
          this.DicData.paymentTermsData = data;
        });
        //单位
        this.getDicData('MATERIAL_UNIT').then((data) => {
          this.DicData.materialUnitData = data;
        });
        //采购类型
        this.getDicData('PURCHASE_TYPE').then((data) => {
          this.DicData.purchasetypeData = data;
        });


        //物流方式
        this.getDicData('MODE_OF_TRANSPORT').then((data) => {
          this.DicData.MODE_OF_TRANSPORT = data;
        });


        // 获取采购组织
        this.getSelectData('post', this.lib.config.host.masterData + '/system/purOrgMgt/purOrg/getPurOrgByUserId/' + this.getCurrUserId(), {}, 'id', 'purOrgName').then((data) => {
          this.purOrgData = data;
        })
      },
      initGroupData(orgId) {
        this.selectPurOrgId = orgId;
        // 获取erp采购组
        this.getSelectData('post', this.lib.config.host.masterData + '/mdata/purOrgMgt/purGroup/getByPurOrgId/' + orgId, {}, 'id', 'purGroupName').then((data) => {
          this.purGroupData = data;
        })
      },
      searchTrans() {
        this.selectVendorData.forEach(element => {
          element.id = element.vendorId;
        })
        this.selectData = this.selectVendorData;
        this.$nextTick(() => {
          this.$refs.trans.searchTrans({pageNo: 1, pageSize: 10});
        })
      },
      changeValue(val) {
        let obj = {};
        obj = this.DicData.paymentTermsData.find((item) => {
          return item.id === val;//筛选出匹配数据
        });
        this.addMaterData.paymentTermsName = obj.name
      },
      changeValueLogisticsMode(val) {
        if (val == 1) {
          this.addMaterData.logisticsMode = '待定'
        }
        if (val == 2) {
          this.addMaterData.logisticsMode = '供商按小时要货'
        }
        if (val == 3) {
          this.addMaterData.logisticsMode = '第三方库发货'
        }
        if (val == 4) {
          this.addMaterData.logisticsMode = '供商按天送货'
        }
      },
      //获取报价模版名称
      changeValuetemplate(val) {


        if (val == 1) {
          this.addMaterData.templateName = '报单价'
        }
        if (val == 2) {
          this.addMaterData.templateName = '分项报价'
        }
        if (val == 3) {
          this.addMaterData.templateName = '按明细报价'
        }
      },
      //设置时间
      checkEndDate(val) {
        if (val < this.addMaterData.priceStartDate + 1) {
          this.$message('结束时间不能大于开始时间！');
          this.addMaterData.priceEndDate = ''
          return false
        }

      },
      AddTime(val) {
        if (this.rfqMainData.quoLimitTime && val) {
          this.rfqMainData.quoLimitTime = this.rfqMainData.quoLimitTime + ' ' + val + ':' + '00'
        }
        else {
          this.$message('请选择日期和时间！');
        }
      },
      //添加分段信息
      addRechargingData() {
        let data = {};
        data.name = this.RechargingName;
        data.val = this.RechargingVal
        this.RechargingData.push(data)
      },
      //删除分段信息
      delRechargingData(index) {
        this.RechargingData.splice(index, 1);
      },
      //清空分段价格
      ClearMaterialData() {
        this.RechargingData = [];
      },
      handleChange(file, fileList) {
      },

      // 暂存物料信息
      submitMaterialData() {
        let data=[];
        Object.keys(this.checkcategorysName).forEach(k=>{
          let categorys=this.checkcategorysName[k];
          data.push({
            ...this.addMaterData,
            purOrgName:categorys.text[0],
            factoryName:categorys.text.slice(1,categorys.text.length).join(','),
            factIds:categorys.ids
          })
        })
        this.tableMaterialData.push(...data);
      },
      //删除物料信息
      delMaterialData(index) {
        this.tableMaterialData.splice(index, 1);
      },
      addMaterial() {
        this.addMaterData.materialId = '';
        this.dialogFormVisible = true;
        this.$nextTick(() => {
          this.resetForm('addOrUpdateForm');
          this.resetFac();
        })
      },
      addTrans(data) {
        this.dataVendorList = this.selectData
      },
      //获取显示的字段
      getLabel(data) {
        let ndata = JSON.parse(JSON.stringify(data));
        let text = '';
        Object.keys(ndata).forEach(k => {
          let first = ndata[k].text.length === 1 ? ndata[k].text[0] : ndata[k].text[0] + ':';
          ndata[k].text.splice(0, 1);
          text += `${first}${ndata[k].text.join(',')}\n`
        })
        return text
      },
      //选择区域处理
      handleCheckAllChange(val, data) {
        if (val) {
          this.addMaterData.factIds.push(data.id);
          this.checkcategorysName[data.id] = {
            text: [data.purOrgName],
            ids: [data.id]
          }
        } else {
          this.addMaterData.factIds.splice(this.addMaterData.factIds.findIndex(val => {
            return val === data.id
          }), 1)
          delete this.checkcategorysName[data.id]
        }
        data.factoryList.forEach(item => {
          item.checked = val;
          if (val) {
            this.addMaterData.factIds.push(item.id);
            this.checkcategorysName[data.id].text.push(item.factoryName);
            this.checkcategorysName[data.id].ids.push(item.id);
          } else {
            this.addMaterData.factIds.splice(this.addMaterData.factIds.findIndex(val => {
              return val === item.id
            }), 1)
          }
        })
        this.addMaterData.showTextarea = this.getLabel(this.checkcategorysName);
        this.$refs.addOrUpdateForm.validateField('showTextarea');
        this.resetMater();
      },
      //选择工厂处理
      handleCheckedChange(item, key, data) {
        if (item) {
          if (!this.checkcategorysName[key.id]) {
            key.checkAll = true;
            this.checkcategorysName[key.id] = {
              text: [key.purOrgName, data.factoryName],
              ids: [key.id, data.id]
            }
            this.addMaterData.factIds.push(...[key.id, data.id]);
          } else {
            this.checkcategorysName[key.id].text.push(data.factoryName);
            this.checkcategorysName[key.id].ids.push(data.id);
            this.addMaterData.factIds.push(data.id);
          }
        } else {
          this.addMaterData.factIds.splice(this.addMaterData.factIds.findIndex(val => {
            return val === data.id
          }), 1);
          this.checkcategorysName[key.id].text.splice(this.checkcategorysName[key.id].text.findIndex(val => {
            return val === data.factoryName
          }), 1);
          this.checkcategorysName[key.id].ids.splice(this.checkcategorysName[key.id].ids.findIndex(val => {
            return val === data.id
          }), 1);
        }
        if (this.checkcategorysName[key.id].text.length === 1) {
          key.checkAll = false;
          this.handleCheckAllChange(false, key);
        } else {
          this.addMaterData.showTextarea = this.getLabel(this.checkcategorysName);
          this.resetMater();
          this.$refs.addOrUpdateForm.validateField('showTextarea');
        }
      },
      //新增物料
      addMaster() {
        this.addMaterData.materialId = '';
        this.dialogFormVisible = true;
        this.$nextTick(() => {
          this.resetForm('addMaterForm');
          this.resetFac();
        })
      },
      //新增重置工厂选择项
      resetFac() {
        this.addMaterData.showTextarea = '';
        this.checkcategorysName = {};
        this.addMaterData.factIds = [];
        this.categoryOptions.forEach(item => {
          item.checkAll = false;
          item.factoryList.forEach(val => {
            val.checked = false;
          })
          item.showList = false;
        })
      },
      //重置物料信息
      resetMater() {
        this.addMaterData.materialId = '';
        this.addMaterData.materialName = '';
        this.addMaterData.materialCode = '';
        this.addMaterData.materialUnit = '';
        this.addMaterData.stockUnit = '';
      },
      changeMater() {
        if (this.checked) {
          this.resetMater();
        }
        this.resetFac();
      },
      //获取物料信息
      getRowData(data) {
        this.addMaterData.materialId = data.materialId;
        this.addMaterData.materialName = data.materialName;
        this.addMaterData.materialCode = data.materialCode;
        this.addMaterData.materialUnit = data.purUnitName;
        this.addMaterData.stockUnit = data.stockUnitName;
      },
      //发布提交
      submitAllData() {
        /*  组合所有数据
          rfqMainData：主要信息
          tableMaterialData：物料信息
          dataVendorList：供应商信息
        */

        this.rfqMainData.sendNoticeTypes = this.rfqMainData.sendNoticeTypes.reduce((prev, curr, index) => prev.concat(curr ? [index] : []), [])
        let curl = this.lib.config.host.rfq + '/ctmgt/rfq/enquiry/saveOrUpdate';

        this.tableMaterialData.forEach(element => {
          delete element.showTextarea;
          delete element.factoryIds;
        })
        let vendorsJsonStr=this.vendorsJsonStr.map(item=>{
          return{
            vendorId:item.id,
            vendorCode:item.vendorCode,
            vendorName:item.vendorName,
          }
        })
        let data = {
          ...this.rfqMainData,
          rfqMaterialsJsonStr: JSON.stringify(this.tableMaterialData),
          rfqVendorsJsonStr: JSON.stringify(vendorsJsonStr)
        }

        console.log(data)
        this.axios.post(curl, data).then((res) => {
          // 保存后跳转到主页面
          if (res.data.success) {
            this.$message('添加成功！');
            this.$router.push({
              path: '/Index/Rfq/RfqEnquiry',
            })

          }
        })
          .catch(function (error) {
            this.$message(error);
          });


      }
    },
  }


</script>
